﻿function employeeModify() {
    SetWait($("body", parent.document), true);
    $.get("../BodyGUI/GetSingleTable",
    { objectID: '', objectType: 'employees' },
     function (data, status) {
         if (status == "success") {
             var dataJson = eval("(" + data + ")");
             buildEmployeeModifyGrid(dataJson);
         }
         SetWait($("body", parent.document), false);
     });
}

function buildEmployeeModifyGrid(dataJson) {
    employeesJsonData = dataJson;
    var source = {
        datatype: "json",
        datafields: [
                        { name: 'employeeID' },
                        { name: 'onDepartment' },
                        { name: 'name' },
                        { name: 'introduction' }
        ],
        id: 'employeeID',
        localdata: dataJson,
        updaterow: function (rowid, rowdata, commit) {
            innerEmployeeModifyRow(rowid, rowdata, commit);
        }
    };
    var dataAdapter = new $.jqx.dataAdapter(source);
    var theme = "";

    var numberrenderer = function (row, column, value) {
        return '<div style="text-align: center; margin-top: 5px;">-' + (1 + value) + '-</div>';
    }

    $("#employeesGrid").jqxGrid(
            {
                enabletooltips: true,
                editable: true,
                localization: getLocalization(),
                selectionmode: 'singlerow',
                editmode: 'dblclick',
                width: '100%',
                height: '100%',
                pageable: true,
                sortable: true,
                source: dataAdapter,
                theme: theme,
                columnsresize: true,
                showsortmenuitems: false,
                columns: [{ resizable: false, sortable: false, pinned: true, exportable: false, text: "", columntype: 'number', cellclassname: 'jqx-widget-header', cellsrenderer: numberrenderer },
                  { editable: false, text: '员工号', datafield: 'employeeID', width: 250 },
                  { text: '在部门', datafield: 'onDepartment', width: 250 },
                  { text: '姓名', datafield: 'name', width: 250 },
                  { text: '简介', datafield: 'introduction', width: 250}],
                toolbarheight: 34,
                showtoolbar: true,
                rendertoolbar: function (toolbar) {
                    var container = $("<div style='margin: 5px;'></div>");
                    var span = $("<span style='float: left; margin-top: 5px; margin-right: 4px;'>员工列表: </span>");
                    //var input = $("<input class='jqx-input jqx-widget-content jqx-rc-all' id='searchField' type='text' style='clear:left;height: 23px; float: left; width: 223px;' />");
                    toolbar.append(container);
                    container.append(span);
                    //container.append(input);

                }

            });
}

function departmentModify() {
    SetWait($("body", parent.document), true);
    $.get("../BodyGUI/GetSingleTable",
    { objectID: '', objectType: 'departments' },
    function (data, status) {
        if (status == "success") {
            var dataJson = eval("(" + data + ")");
            buildDepartmentModifyGrid(dataJson);
        }
        SetWait($("body", parent.document), false);
    });
}

function buildDepartmentModifyGrid(dataJson) {
    departmentsJsonData = dataJson;
    var source = {
        datatype: "json",
        datafields: [
                        { name: 'departmentID' },
                        { name: 'departmentName' },
                        { name: 'departmentTotal' },
                        { name: 'departmentIntroduction' },
                        { name: 'parentDepartment' }
        ],
        id: 'departmentID',
        localdata: dataJson
    };
    var dataAdapter = new $.jqx.dataAdapter(source);
    var theme = "";

    var numberrenderer = function (row, column, value) {
        return '<div style="text-align: center; margin-top: 5px;">-' + (1 + value) + '-</div>';
    }

    $("#departmentsGrid").jqxGrid(
            {
                enabletooltips: true,
                editable: false,
                localization: getLocalization(),
                selectionmode: 'singlerow',
                editmode: 'dblclick',
                width: '100%',
                height: '100%',
                pageable: true,
                sortable: true,
                source: dataAdapter,
                theme: theme,
                columnsresize: true,
                showsortmenuitems: false,
                columns: [{ resizable: false, sortable: false, pinned: true, exportable: false, text: "", columntype: 'number', cellclassname: 'jqx-widget-header', cellsrenderer: numberrenderer },
                  { editable: false, text: '部门号', datafield: 'departmentID', width: 250 },
                  { text: '部门名', datafield: 'departmentName', width: 250 },
                  { text: '部门人数', datafield: 'departmentTotal', width: 250 },
                  { text: '简介', datafield: 'departmentIntroduction', width: 250 },
                  { text: '父部门', datafield: 'parentDepartment', width: 250}],
                toolbarheight: 34,
                showtoolbar: true,
                rendertoolbar: function (toolbar) {
                    var container = $("<div style='margin: 5px;'></div>");
                    var span = $("<span style='float: left; margin-top: 5px; margin-right: 4px;'>部门列表: </span>");
                    //var input = $("<input class='jqx-input jqx-widget-content jqx-rc-all' id='searchField' type='text' style='clear:left;height: 23px; float: left; width: 223px;' />");
                    toolbar.append(container);
                    container.append(span);
                    //container.append(input);
                }

            });
}

function initDelEmployeeDialogConfirm() {
    $("#dialog-confirm").dialog({
        autoOpen: false,
        resizable: false,
        height: 180,
        modal: true,
        buttons: {
            "确定": function () {
                $(this).dialog("close");
                deleteEmployeeRow();
            },
            "取消": function () {
                $(this).dialog("close");
            }
        }
    });
}

function initDelDepartmentDialogConfirm() {
    $("#dialog-confirm").dialog({
        autoOpen: false,
        resizable: false,
        height: 180,
        modal: true,
        buttons: {
            "确定": function () {
                $(this).dialog("close");
                deleteDepartmentRow();
            },
            "取消": function () {
                $(this).dialog("close");
            }
        }
    });
}

function initDialogModifyEmployee() {
    $("#dialog-modifyEmployee").dialog({
        autoOpen: false,
        height: 390,
        width: 400,
        modal: true,
        buttons: {
            "确定": function () {
                var bValid = true;
                allFields.removeClass("ui-state-error");
                bValid = bValid && checkLength($("#input_onDepartment"), "在部门", 1, 5);
                bValid = bValid && checkLength($("#input_name"), "姓名", 1, 20);
                bValid = bValid && checkLength($("#input_introduction"), "介绍", 0, 45);
                bValid = bValid && checkRegexp($("#input_onDepartment"), /^[0-9]*$/, "[在部门] 必须是一个整数.");
                bValid = bValid && checkRegexp($("#input_name"), /^(?!_)(?!.*?_$)[a-zA-Z_\u4e00-\u9fa5]+$/i, "姓名 必须只含有汉字、字母、下划线，不能以下划线开头和结尾。");

                if (bValid) {
                    $(this).dialog("close");
                    addEmployeeRow($("#input_onDepartment").val(), $("#input_name").val(), $("#input_introduction").val());
                }
            },
            "取消": function () {
                $(this).dialog("close");
            }
        },

        close: function () {
            allFields.val("").removeClass("ui-state-error");
        }
    });
}

function initDialogModifyDepartment() {
 $("#dialog-modifyDepartment").dialog({autoOpen: false});
}

var allFields = $([]).add($("#input_onDepartment")).add($("#input_name")).add($("#input_introduction"))
var allFields2 = $([]).add($("#input_departmentName")).add($("#input_departmentTotal")).add($("#input_departmentIntroduction")).add($("#input_parentDepartment"))

function updateTips(t) {
    $(".validateTips")
        .text(t)
        .addClass("ui-state-highlight");
    setTimeout(function () {
        $(".validateTips").removeClass("ui-state-highlight", 1500);
    }, 500);

}

function checkLength(o, n, min, max) {
    if (o.val().length > max || o.val().length < min) {
        o.addClass("ui-state-error");
        updateTips("[" + n + "] 的长度必须介于" +
          min + " 和 " + max + "之间。");
        return false;
    } else {
        return true;
    }
}

function checkRegexp(o, regexp, n) {
    if (!(regexp.test(o.val()))) {
        o.addClass("ui-state-error");
        updateTips(n);
        return false;
    } else {
        return true;
    }
}

function innerEmployeeModifyRow(rowid, rowdata, commit) {
    SetWait($("body", parent.document), true);
    $.post("../BodyGUI/UpdateEmployee",
    { commitType: 'modify',
        modifyEmployee: (rowdata.employeeID + ',' + rowdata.onDepartment + ',' + rowdata.name + ',' + rowdata.introduction)
    },
    function (data, status) {
        if (status == "success") {
            if (data == 'True')
                commit(true);
            else
                commit(false);
        }
        SetWait($("body", parent.document), false);
    });
}

function deleteEmployeeRow() {
    var selectedrowindex = $("#employeesGrid").jqxGrid('getselectedrowindex');
    var rowscount = $("#employeesGrid").jqxGrid('getdatainformation').rowscount;
    if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
        SetWait($("body", parent.document), true);
        var rowid = $("#employeesGrid").jqxGrid('getrowid', selectedrowindex);
        $.post("../BodyGUI/UpdateEmployee",
    { commitType: 'delete',
        modifyEmployee: rowid
    },
    function (data, status) {
        if (status == "success") {
            if (data != 'False') {
                var commit = $("#employeesGrid").jqxGrid('deleterow', rowid);
            }
        }
        SetWait($("body", parent.document), false);
    });
    }
}

function deleteDepartmentRow() {
    var selectedrowindex = $("#departmentsGrid").jqxGrid('getselectedrowindex');
    var rowscount = $("#departmentsGrid").jqxGrid('getdatainformation').rowscount;
    if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
        SetWait($("body", parent.document), true);
        var rowid = $("#departmentsGrid").jqxGrid('getrowid', selectedrowindex);
        $.post("../BodyGUI/UpdateDepartment",
             { commitType: 'delete',
                 modifyDepartment: rowid
             },
            function (data, status) {
                if (status == "success") {
                    if (data != 'False') {
                        var commit = $("#departmentsGrid").jqxGrid('deleterow', rowid);
                    }
                }
                SetWait($("body", parent.document), false);
            });
    }
}

function addDepartmentRow(departmentName, departmentTotal, departmentIntroduction, parentDepartment) {
    SetWait($("body", parent.document), true);
    var rowdata = {};
    rowdata["departmentID"] = -1;
    rowdata["departmentName"] = departmentName;
    rowdata["departmentTotal"] = departmentTotal;
    rowdata["departmentIntroduction"] = departmentIntroduction;
    rowdata["parentDepartment"] = parentDepartment;

    $.post("../BodyGUI/UpdateDepartment",
    {
        commitType: 'add',
        modifyDepartment: (rowdata.departmentID + ',' + rowdata.departmentName + ',' + rowdata.departmentTotal + ',' + rowdata.departmentIntroduction + ',' + rowdata.parentDepartment)
    },
    function (data, status) {
        if (status == "success") {
            if (data != 'False') {
                rowdata["departmentID"] = data;
                var commit = $("#departmentsGrid").jqxGrid('addrow', rowdata["departmentID"], rowdata);
            }
        }
        SetWait($("body", parent.document), false);
    });
}

function addEmployeeRow(onDepartment, name, introduction) {
    SetWait($("body", parent.document), true);
    var rowdata = {};
    rowdata["employeeID"] = -1;
    rowdata["onDepartment"] = onDepartment;
    rowdata["name"] = name;
    rowdata["introduction"] = introduction;
    $.post("../BodyGUI/UpdateEmployee",
    {
        commitType: 'add',
        modifyEmployee: (rowdata.employeeID + ',' + rowdata.onDepartment + ',' + rowdata.name + ',' + rowdata.introduction)
    },
    function (data, status) {
        if (status == "success") {
            if (data != 'False') {
                rowdata["employeeID"] = data;
                var commit = $("#employeesGrid").jqxGrid('addrow', rowdata["employeeID"], rowdata);
            }
        }
        SetWait($("body", parent.document), false);
    });
}

function showDeleteDepartmentRowDialog() {
    var selectedrowindex = $("#departmentsGrid").jqxGrid('getselectedrowindex');
    var rowscount = $("#departmentsGrid").jqxGrid('getdatainformation').rowscount;
    if (selectedrowindex >= 0 && selectedrowindex < rowscount)
    { $("#dialog-confirm").dialog("open"); }
}

function showDeleteEmployeeRowDialog() {
    var selectedrowindex = $("#employeesGrid").jqxGrid('getselectedrowindex');
    var rowscount = $("#employeesGrid").jqxGrid('getdatainformation').rowscount;
    if (selectedrowindex >= 0 && selectedrowindex < rowscount)
    { $("#dialog-confirm").dialog("open"); }
}

function modifyDepartmentValid() {
    var bValid = true;
    allFields2.removeClass("ui-state-error");
    bValid = bValid && checkLength($("#input_departmentName"), "部门名", 1, 30);
    bValid = bValid && checkRegexp($("#input_departmentName"), /^(?!_)(?![0-9])(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/i, "部门名 必须只含有汉字、字母、下划线，开头可以是汉字或字母，结尾可以是汉字或字母或数字。");

    bValid = bValid && checkLength($("#input_departmentTotal"), "部门人数", 1, 5);
    bValid = bValid && checkRegexp($("#input_departmentTotal"), /^[0-9]*$/, "[部门人数] 必须是一个整数.");

    bValid = bValid && checkLength($("#input_departmentIntroduction"), "介绍", 1, 30);

    bValid = bValid && checkLength($("#input_parentDepartment"), "父部门", 1, 5);
    bValid = bValid && checkRegexp($("#input_parentDepartment"), /^[0-9]*$/, "[父部门] 必须是一个整数.");

    return bValid;
}

function showAddDepartmentRowDialog() {
    $("#dialog-modifyDepartment").dialog("option", "title", "创建新部门");
    $("#dialog-modifyDepartment").dialog({
        autoOpen: false,
        height: 440,
        width: 400,
        modal: true,
        buttons: {
            "确定": function () {
                var bValid = modifyDepartmentValid();

                if (bValid) {
                    $(this).dialog("close");
                    addDepartmentRow($("#input_departmentName").val(), $("#input_departmentTotal").val(), $("#input_departmentIntroduction").val(), $("#input_parentDepartment").val());
                }
            },
            "取消": function () {
                $(this).dialog("close");
            }
        },

        close: function () {
            allFields2.val("").removeClass("ui-state-error");
        }
    });
    $("#dialog-modifyDepartment").dialog("open");
}

function showAddEmployeeRowDialog() {
    $("#dialog-modifyEmployee").dialog("open");
}

function showModifyDepartmentRowDialog() {
    var selectedrowindex = $("#departmentsGrid").jqxGrid('getselectedrowindex');
    var rowscount = $("#departmentsGrid").jqxGrid('getdatainformation').rowscount;
    if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
        var rowid = $("#departmentsGrid").jqxGrid('getrowid', selectedrowindex);
        var rowdata = $('#departmentsGrid').jqxGrid('getrowdatabyid', rowid);
        $("#input_departmentName").val(rowdata.departmentName);
        $("#input_departmentTotal").val(rowdata.departmentTotal);
        $("#input_departmentIntroduction").val(rowdata.departmentIntroduction);
        $("#input_parentDepartment").val(rowdata.parentDepartment);

        $("#dialog-modifyDepartment").dialog("option", "title", "修改部门");
        $("#dialog-modifyDepartment").dialog({
            autoOpen: false,
            height: 440,
            width: 400,
            modal: true,
            buttons: {
                "确定": function () {
                    var bValid = modifyDepartmentValid();

                    if (bValid) {
                        $(this).dialog("close");
                        
                        modifyDepartmentRow(rowid,$("#input_departmentName").val(), $("#input_departmentTotal").val(), $("#input_departmentIntroduction").val(), $("#input_parentDepartment").val());
                    }
                },
                "取消": function () {
                    $(this).dialog("close");
                }
            },

            close: function () {
                allFields2.val("").removeClass("ui-state-error");
            }
        });
        $("#dialog-modifyDepartment").dialog("open");    
    }
}

function modifyDepartmentRow(departmentID, departmentName, departmentTotal, departmentIntroduction,parentDepartment) {
    SetWait($("body", parent.document), true);
    $.post("../BodyGUI/UpdateDepartment",
    { commitType: 'modify',
        modifyDepartment: (departmentID + ',' + departmentName + ',' + departmentTotal + ',' + departmentIntroduction + ',' + parentDepartment)
    },
    function (data, status) {
        if (status == "success") {
            if (data == 'True')
                var rowdata = {};
            rowdata["departmentID"] = departmentID;
            rowdata["departmentName"] = departmentName;
            rowdata["departmentTotal"] = departmentTotal;
            rowdata["departmentIntroduction"] = departmentIntroduction;
            rowdata["parentDepartment"] = parentDepartment;
            
            $("#departmentsGrid").jqxGrid('updaterow', departmentID, rowdata);
        }
        SetWait($("body", parent.document), false);
    });
}

function refreshEmployee() {
    SetWait($("body", parent.document), true);
    $.get("../BodyGUI/GetSingleTable",
    { objectID: '', objectType: 'employees' },
    function (data, status) {
        if (status == "success") {
            var dataJson = eval("(" + data + ")");
            $("#employeesGrid").jqxGrid('source')._source.localdata = dataJson;
            $("#employeesGrid").jqxGrid('updatebounddata', 'cells');
        }
        SetWait($("body", parent.document), false);
    });
}

function refreshDepartment() {
    SetWait($("body", parent.document), true);
    $.get("../BodyGUI/GetSingleTable",
    { objectID: '', objectType: 'departments' },
    function (data, status) {
        if (status == "success") {
            var dataJson = eval("(" + data + ")");
            $("#departmentsGrid").jqxGrid('source')._source.localdata = dataJson;
            $("#departmentsGrid").jqxGrid('updatebounddata', 'cells');
        }
        SetWait($("body", parent.document), false);
    });
}

function employeeModifyButtonClk(ui) {

    switch (ui.attr("name")) {
        case "employeeAdd":
            showAddEmployeeRowDialog();
            break;
        case "employeeDel":
            showDeleteEmployeeRowDialog();
            break;
        case "employeeRefresh":
            refreshEmployee();
            break;
        default:
    }
}

function departmentModifyButtonClk(ui) {

    switch (ui.attr("name")) {
        case "departmentAdd":
            showAddDepartmentRowDialog();
            break;
        case "departmentDel":
            showDeleteDepartmentRowDialog();
            break;
        case "departmentMod":
            showModifyDepartmentRowDialog();
            break;
        case "departmentRefresh":
            refreshDepartment();
            break;
        default:
    }
}